import { Form, Input, Checkbox, Button, message } from "antd"
import { UserOutlined, LockOutlined } from "@ant-design/icons"
import { useDispatch } from "react-redux"
import { login } from "@/store/actions/user"
import { useHistory, useLocation } from "react-router-dom"
import logo from "@/assets/logo.png"

import "./index.scss"
const mobileRules = [
  {
    required: true,
    message: "手机号不能为空",
  },
  {
    pattern: /^1[3-9]\d{9}$/,
    message: "手机号格式不正确",
  },
]
const codeRules = [
  {
    required: true,
    message: "验证码不能为空",
  },
  {
    pattern: /^\d{6}$/,
    message: "验证码的格式不正确",
  },
]
const agreeRules = [
  {
    validator: (_, value) => {
      // value为true表示勾选否则不让过
      return value
        ? Promise.resolve()
        : Promise.reject(new Error("没有勾选用户协议条款"))
    },
  },
]
const initialValues = {
  mobile: "13911111111",
  code: "246810",
  isAgree: true,
}
const Login = () => {
  // 要获取路由推过来的数据
  const location = useLocation()
  const dispatch = useDispatch() // 相当于 store.dispatch()
  const history = useHistory() // 得到对象
  const onFinish = async (values) => {
    // 只有验证通过才会进入该函数
    // 调用action  触发登录操作
    try {
      await dispatch(login(values)) // 登录成功 登录失败
      message.success("登录成功")
      history.replace(location?.state?.from || "/") // 跳到首页
      // 登录成功
    } catch (error) {
      console.log(error)
      message.error("登录失败")
    }
  }

  return (
    <div className="login">
      <div className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          initialValues={initialValues}
          onFinish={onFinish}
          size="large"
          validateTrigger={["onBlur"]}
        >
          <Form.Item name="mobile" rules={mobileRules}>
            <Input prefix={<UserOutlined />}></Input>
          </Form.Item>
          <Form.Item name="code" rules={codeRules}>
            <Input prefix={<LockOutlined />}></Input>
          </Form.Item>
          <Form.Item name="isAgree" valuePropName="checked" rules={agreeRules}>
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>
          <Form.Item>
            <Button type="primary" block htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
